import math
import paddle
import paddle.nn.functional as F
import numpy as np
from model.xception import Xception
# 参考链接
# blog.csdn.net/weixin_44791964/article/details/103017389
# 跨卡GPU同步的批归一化
BatchNorm2d = paddle.nn.BatchNorm2D

class ASPP_module(paddle.nn.Layer):  # ASpp模块的组成
    def __init__(self, inplanes, planes, dilation):
        super(ASPP_module, self).__init__()
        if dilation == 1:
            kernel_size = 1
            padding = 0
        else:
            kernel_size = 3
            padding = dilation
        self.atrous_convolution = paddle.nn.Conv2D(inplanes, planes, kernel_size=kernel_size,
                                            stride=1, padding=padding, dilation=dilation, bias_attr=False)
        self.bn = BatchNorm2d(planes)
        self.relu = paddle.nn.ReLU()
        # self._init_weight()

    def forward(self, x):
        x = self.atrous_convolution(x)
        x = self.bn(x)
        return self.relu(x)

    # 初始化权重
    # def _init_weight(self):
    #     for m in self.modules():
    #         if isinstance(m, paddle.nn.Conv2D):
    #             n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
    #             m.weight.data.normal_(0, math.sqrt(2. / n))
    #         elif isinstance(m, BatchNorm2d):
    #             m.weight.data.fill_(1)
    #             m.bias.data.zero_()


# 正式开始deeplabv3+的结构组成
class DeepLabv3p(paddle.nn.Layer):
    def __init__(self, nInputChannels=3, n_classes=8, os=16, pretrained=False, freeze_bn=False, _print=True):
        if _print:
            print("Constructing DeepLabv3+ model...")
            print("Backbone: Resnet-101")
            print("Number of classes: {}".format(n_classes))
            print("Output stride: {}".format(os))
            print("Number of Input Channels: {}".format(nInputChannels))
        super(DeepLabv3p, self).__init__()

        self.xception = Xception(n_classes)
        # ASPP,挑选参数
        if os == 16:
            dilations = [1, 6, 12, 18]
        elif os == 8:
            dilations = [1, 12, 24, 36]
        else:
            raise NotImplementedError
        # 四个不同带洞卷积的设置，获取不同感受野
        self.aspp1 = ASPP_module(2048, 256, dilation=dilations[0])
        self.aspp2 = ASPP_module(2048, 256, dilation=dilations[1])
        self.aspp3 = ASPP_module(2048, 256, dilation=dilations[2])
        self.aspp4 = ASPP_module(2048, 256, dilation=dilations[3])
        self.relu = paddle.nn.ReLU()

        # 全局平均池化层的设置
        self.global_avg_pool = paddle.nn.Sequential(paddle.nn.AdaptiveAvgPool2D((1, 1)),
                                             paddle.nn.Conv2D(2048, 256, 1, stride=1, bias_attr=False),
                                             BatchNorm2d(256),
                                             paddle.nn.ReLU())

        self.conv1 = paddle.nn.Conv2D(1280, 256, 1, bias_attr=False)
        self.bn1 = BatchNorm2d(256)

        # adopt [1x1, 48] for channel reduction.
        self.conv2 = paddle.nn.Conv2D(256, 48, 1, bias_attr=False)
        self.bn2 = BatchNorm2d(48)
        # 结构图中的解码部分的最后一个3*3的卷积块
        self.last_conv = paddle.nn.Sequential(paddle.nn.Conv2D(304, 256, kernel_size=3, stride=1, padding=1, bias_attr=False),
                                       BatchNorm2d(256),
                                       paddle.nn.ReLU(),
                                       paddle.nn.Conv2D(256, 256, kernel_size=3, stride=1, padding=1, bias_attr=False),
                                       BatchNorm2d(256),
                                       paddle.nn.ReLU(),
                                       paddle.nn.Conv2D(256, n_classes, kernel_size=1, stride=1))

        if freeze_bn:
            self._freeze_bn()
        # 初始化权重
        # for m in self.sublayers():
        #     if isinstance(m, paddle.nn.Conv2D):
        #         paddle.nn.initializer.KaimingNormal(m.weight, mode='fan_out', nonlinearity='relu')
        #     elif isinstance(m, paddle.nn.BatchNorm2D):
        #         paddle.nn.initializer.constant_(m.weight, 1)
        #         paddle.nn.initializer.constant_(m.bias, 0)

    # 前向传播
    def forward(self, input):
        # x, low_level_features = self.resnet_features(input)
        x, low_level_features = self.xception(input)
        x1 = self.aspp1(x)
        x2 = self.aspp2(x)
        x3 = self.aspp3(x)
        x4 = self.aspp4(x)
        x5 = self.global_avg_pool(x)
        print('x4', low_level_features.shape)
        x5 = F.upsample(x5, size=x4.shape[2:], mode='bilinear', align_corners=True)
        # 把四个ASPP模块以及全局池化层拼接起来
        x = paddle.concat((x1, x2, x3, x4, x5), axis=1)
        # 上采样
        x = self.conv1(x)
        x = self.bn1(x)
        x = self.relu(x)
        x = F.upsample(x, size=(int(math.ceil(input.shape[-2] / 4)),
                                int(math.ceil(input.shape[-1] / 4))), mode='bilinear', align_corners=True)

        low_level_features = self.conv2(low_level_features)
        low_level_features = self.bn2(low_level_features)
        low_level_features = self.relu(low_level_features)

        # 拼接低层次的特征，然后再通过插值获取原图大小的结果
        x = paddle.concat((x, low_level_features), axis=1)
        x = self.last_conv(x)
        # 实现插值和上采样
        print(input.shape, input.size)
        x = F.interpolate(x, size=input.shape[2:], mode='bilinear', align_corners=True)
        return x


if __name__ == "__main__":
    model = DeepLabv3p(nInputChannels=3, n_classes=21, os=16, pretrained=True, _print=True)
    model.eval()
    image = paddle.randn(shape=[1, 3, 512, 512], dtype='float32')

    with paddle.no_grad():
        output = model.forward(image)
    print(output.shape)